package com.jiangdg.usbcamera.view;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.jiangdg.usbcamera.R;
import com.jiangdg.usbcamera.login.LoginInfo;
import com.jiangdg.usbcamera.utils.HttpUtils;
import com.jiangdg.usbcamera.utils.SPUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.MyViewHolder>{
    Context context;
    private View inflater;
    ArrayList<PhotoBean> list;

    public PhotoAdapter(Context context, ArrayList<PhotoBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public PhotoAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        inflater = LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(inflater);
        return myViewHolder;
//        return new RecyclerView.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        //将数据和控件绑定
        holder.box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                list.get(position).setChosed(  b  );
                if(b && (!list.get(position).isHasUpload())){
                    postToServer(list.get(position).getUrl(),position);
                }
            }
        });
        if(list.get(position).getUrl().endsWith(".jpg")){
//            Glide.with(context).load(  getMediaUriFromPath(context,list.get(position).getUrl())).into(holder.img);
            Glide.with(context).load(  new File( list.get(position).getUrl()))
                    .skipMemoryCache(true) // 不使用内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(holder.img);
        }else {
            Glide.with(context).load(R.mipmap.img_shiping).into(holder.img);
        }


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    //内部类，绑定控件
    class MyViewHolder extends RecyclerView.ViewHolder{
        ImageView img;
        CheckBox box;
        public MyViewHolder(View itemView) {
            super(itemView);
            img = (ImageView) itemView.findViewById(R.id.img);
            box = (CheckBox) itemView.findViewById(R.id.cb);
        }
    }



    //上传文件到服务器
    private void postToServer(String path,int postion) {
        RequestParams params = new RequestParams();
        try {
            params.put("file", new File(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        String user = (String) SPUtils.get(context, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(user.toString(), LoginInfo.class);

        info.getToken();
        HttpUtils.httpPostMethod("http://api.bonjourmed.com/file/temp?auth=" + info.getToken(), params, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {

                    Log.d("RESULT", response.toString());
                    if (response.getBoolean("status")) {

                        Toast.makeText(context, "上传完成", Toast.LENGTH_SHORT).show();
//                        images.add();
//                        list.get(postion).setUrl( response.getString("msg")) ;
                        list.get(postion).setHasUpload(true);
                        list.get(postion).setId(response.getString("msg"));
                    } else {
                        Toast.makeText(context, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
            }
        });
    }

    public static Uri getMediaUriFromPath(Context context, String path) {
        Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = context.getContentResolver().query(mediaUri,
                null,
                MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                new String[] {path.substring(path.lastIndexOf("/") + 1)},
                null);

        Uri uri = null;
        if(cursor.moveToFirst()) {
            uri = ContentUris.withAppendedId(mediaUri,
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        }
        cursor.close();
        return uri;
    }
}
